package work.huangxin.share.service.impl;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import work.huangxin.share.constant.OssConstant;
import work.huangxin.share.service.OssService;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * @author 季台星
 * @Date 2023 04 13 21 28
 */
@Service
@Slf4j
public class OssServiceImpl implements OssService {

    public String uploadImage(String fileName, File file){
        OSS oss = new OSSClient(OssConstant.ACCESS_ENDPOINT,
                                OssConstant.ACCESS_ID,
                                OssConstant.ACCESS_SECRET);
        PutObjectResult putObjectResult = null;
        try {
            log.info("图片上传开始=======>" + DateTime.now());
            boolean isExist = oss.doesBucketExist(OssConstant.ACCESS_BUCKETNAME);
            if (!isExist){
                log.error("图片上传失败bucket异常");
                throw new RuntimeException("阿里云OSS图床异常");
            }
            PutObjectRequest request  =  new PutObjectRequest(OssConstant.ACCESS_BUCKETNAME,
                    fileName, new FileInputStream(file));
             putObjectResult = oss.putObject(request);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        log.info("图片上传成功！===========>" + DateTime.now());
        return fileName;
    }
}
